package com.lgt_enterprise_android.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSONObject;
import com.dialogs.UpdateAlertDialog;
import com.lgt_enterprise_android.BuildConfig;
import com.lgt_enterprise_android.base.BaseActivity;
import com.util.AppUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by mike.min on 2017/12/27.
 * 应用更新
 */

public class CheckUpdate {

    private Context mContext;

    private UpdateAlertDialog updataDialog;

    boolean isStopDownLoad = false;


    private int mPrecent;

    private static final int MSG_UPDATA_PROGRESS = 3;
    private static final int MSG_DOWNLOAD_FAIL = 4;
    private static final int MSG_INSTALL_FILE = 5;


    /***
     *
     * @param context
     * @param isClick 是否是主动点击更新
     */
    public void checkUpgrade(final Context context, final boolean isClick) {
        mContext = context;

        HttpManager.checkUpdate(context, new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(Object resonseObj) {
                if (resonseObj == null) {
                    return;
                }
                JSONObject jsonObject = (JSONObject) resonseObj;
                JSONObject jsonVersion = jsonObject.getJSONObject("android");
                if (jsonVersion == null) {
                    return;
                }

                int version = 0;

                try {
                    version = jsonVersion.getIntValue("latestVersion");
                } catch (Exception ex) {

                }

                if (AppUtil.getVersionCode(context) >= version) {
                    if (isClick) {
                        Toast.makeText(context, "当前已是最新版本", Toast.LENGTH_SHORT).show();
                    }
                    return;
                } else {
                    if (!isClick && jsonVersion.getIntValue("updateType") == 0) {
                        return;
                    }
                    showNoticeDialog(jsonVersion.getString("describe"), jsonVersion.getString("updateUrl"), jsonVersion.getIntValue("updateType") == 2);
                }
            }

            @Override
            public void onFailure(String mes) {

            }
        });
    }


    //http://lgt-test.ds78.com.cn/static/lgt-e-version.json
    protected void showNoticeDialog(final String updateContent, final String updateLink, boolean isForceUpdate) {

        if (mContext == null) return;

        BaseActivity activity = null;
        if (mContext instanceof BaseActivity) {
            activity = ((BaseActivity) mContext);
        }

        if (activity == null) return;

        if (activity.isFinishing()) {
            return;
        }

        final UpdateAlertDialog dialog = new UpdateAlertDialog(mContext);
        dialog.setTitleText("应用更新");
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentText(updateContent)
                .setPositiveText("更新")
                .setContentTextGravity(Gravity.LEFT).setOnPositiveListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                download(updateLink);
            }
        }).setOnNegativeListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        if (isForceUpdate) {
            dialog.hideNegative();
        } else {
            dialog.setNegativeText("暂不更新");
        }

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub

                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    dialog.dismiss();
                    ((Activity) mContext).finish();
                    return true;
                } else {
                    return false;
                }
            }
        });

        dialog.show();
    }


    /*** 转换文件大小单位(b/kb/mb/gb) ***/
    public String formatFileSize(long fileS) {// 转换文件大小

        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATA_PROGRESS:
                    if (updataDialog != null) {
                        Bundle b = msg.getData();
                        if (b == null) return;
                        updataDialog.setProgress(mPrecent);
//                        updataDialog.setDownLoadText1(formatFileSize(b.getLong("count"))+"/"+formatFileSize(b.getLong("length")));
                    }

                    break;
                case MSG_DOWNLOAD_FAIL:
                    if (updataDialog != null && updataDialog.isShowing())
                        updataDialog.dismiss();
//                     showToast("下载失败，请稍后再试！");

                    break;
                case MSG_INSTALL_FILE:
                    install((File) msg.obj, mContext);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void install(File file, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= 24) { //
            Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");

        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }


        context.startActivity(intent);
    }

    private void download(final String url) {

        updataDialog = new UpdateAlertDialog(mContext);

        updataDialog.setCancelable(false);
        updataDialog.setCanceledOnTouchOutside(false);

        updataDialog.setTitleText("应用更新")
                .hideButtonLyaout()
                .hideEndtag()
                .setProgress(0)
                .hideContentTv()
                .showProgressLayout()
                .setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        // TODO Auto-generated method stub

                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                            isStopDownLoad = true;
                            dialog.dismiss();
                            ((Activity) mContext).finish();
                            return true;
                        } else {
                            return false;
                        }
                    }
                });

        updataDialog.show();

        //创建OkHttpClient对象，用于稍后发起请求

        OkHttpClient client = new OkHttpClient();
        //根据请求URL创建一个Request对象

        Request request = new Request.Builder().url(url).build();

        //根据Request对象发起Get同步Http请求

//        Response response = client.newCall(request).execute();


        //根据Request对象发起Get异步Http请求，并添加请求回调

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                int a = 1;

            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                File mTempFile = new File(mContext.getExternalCacheDir() + "/" + url.substring(url.lastIndexOf("/") + 1));
                if (mTempFile.exists()) {
                    mTempFile.delete();
                }

                InputStream is = response.body().byteStream();
                saveFile(is, response.body().contentLength(), mTempFile);
            }
        });
    }

    private void saveFile(InputStream is, Long length, File mTempFile) {
        if (is != null) {
            try {
                BufferedInputStream bis = new BufferedInputStream(is);
                FileOutputStream fos = new FileOutputStream(mTempFile);
                BufferedOutputStream bos = new BufferedOutputStream(fos);

                int read;
                long count = 0;
                int precent = 0;
                byte[] buffer = new byte[1024];
                while ((read = bis.read(buffer)) != -1 && !isStopDownLoad) {
                    bos.write(buffer, 0, read);
                    count += read;
                    precent = (int) (((double) count / length) * 100);
                    if (precent - mPrecent >= 1) {
                        mPrecent = precent;

                        Message m = Message.obtain(mHandler, MSG_UPDATA_PROGRESS);

                        Bundle bundle = new Bundle();
                        bundle.putLong("count", count);
                        bundle.putLong("length", length);
                        m.setData(bundle);

                        mHandler.sendMessage(m);
                    }
                }
                bos.flush();
                bos.close();
                fos.flush();
                fos.close();
                is.close();
                bis.close();
                if (!isStopDownLoad) {
                    updataDialog.dismiss();
                    Message message = mHandler.obtainMessage(MSG_INSTALL_FILE, mTempFile);
                    mHandler.sendMessage(message);
                } else {
                    updataDialog.dismiss();
                }
            } catch (IOException e) {
                mHandler.sendEmptyMessage(MSG_DOWNLOAD_FAIL);
            } catch (Exception e) {
                mHandler.sendEmptyMessage(MSG_DOWNLOAD_FAIL);
            }
        }
    }
}
